package com.ruoyi.ax.service.impl;

import java.io.BufferedReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.ax.domain.AxAccountChangeRecord;
import com.ruoyi.ax.service.IAxAccountChangeRecordService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.PayStatusEnum;
import com.ruoyi.common.enums.RechargeType;
import com.ruoyi.common.enums.changeSouceType;
import com.ruoyi.common.enums.payTypeEnum;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.common.utils.wx.HttpClientSslUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.ax.mapper.AxRechargeRecordMapper;
import com.ruoyi.ax.domain.AxRechargeRecord;
import com.ruoyi.ax.service.IAxRechargeRecordService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 充值记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-07
 */
@Service
public class AxRechargeRecordServiceImpl implements IAxRechargeRecordService 
{
    @Autowired
    private AxRechargeRecordMapper axRechargeRecordMapper;

    @Autowired
    private ISysUserService userService;

    @Value("${payInfo.terminalCode}")
    private String payTerminalCode;

    @Value("${payInfo.key}")
    private String payKey;




    @Autowired
    private IAxAccountChangeRecordService axAccountChangeRecordService;

    /**
     * 查询充值记录
     * 
     * @param id 充值记录主键
     * @return 充值记录
     */
    @Override
    public AxRechargeRecord selectAxRechargeRecordById(Long id)
    {
        return axRechargeRecordMapper.selectAxRechargeRecordById(id);
    }


    @Override
    @Transactional
    public  int  pcUserRecharge(AxRechargeRecord axRechargeRecord){
        axRechargeRecord.setOrderNumber(getMillseconds());
      //  axRechargeRecord.setSysUserId(SecurityUtils.getUserId()+"");
        axRechargeRecord.setPayStatus(PayStatusEnum.已支付.getCode());
       // axRechargeRecord.setPayWay(payTypeEnum.后台.getInfo());

        long sysUserId= Long.valueOf(axRechargeRecord.getSysUserId()) ;
        SysUser axUser = userService.selectUserById(sysUserId);

        String rechargeTypeInfo="";
        if(axRechargeRecord.getRechargeType().equals(RechargeType.余额.getCode())){
            axUser.setRechargeAmount( String.format("%.2f",Double.valueOf(axUser.getRechargeAmount())+Double.valueOf(axRechargeRecord.getRechargeMoney()),2));
            rechargeTypeInfo = RechargeType.余额.getInfo();
        }else if(axRechargeRecord.getRechargeType().equals(RechargeType.拍品券.getCode())){
            axUser.setAbleConsumeTotalIncome( String.format("%.2f",Double.valueOf(axUser.getAbleConsumeTotalIncome())+Double.valueOf(axRechargeRecord.getRechargeMoney()),2));
            axUser.setTotalIncome(String.format("%.2f",Double.valueOf(axUser.getTotalIncome())+Double.valueOf(axRechargeRecord.getRechargeMoney()),2));
            rechargeTypeInfo = RechargeType.拍品券.getInfo();
        }else if(axRechargeRecord.getRechargeType().equals(RechargeType.津贴券.getCode())){
             axUser.setIndirectIncome( String.format("%.2f",Double.valueOf(axUser.getIndirectIncome())+Double.valueOf(axRechargeRecord.getRechargeMoney()),2));
             axUser.setTotalIncome(String.format("%.2f",Double.valueOf(axUser.getTotalIncome())+Double.valueOf(axRechargeRecord.getRechargeMoney()),2));
             rechargeTypeInfo = RechargeType.津贴券.getInfo();
        }else{
            throw new GlobalException("无该充值类型");
        }
        userService.updateUser(axUser);
       // axRechargeRecord.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        axRechargeRecord.setPayWay(payTypeEnum.后台.getInfo()+"-"+rechargeTypeInfo);
        this.insertAxRechargeRecord(axRechargeRecord);

       // axUser.setRechargeRewardPoints( String.format("%.2f",(Double.valueOf(axUser.getRechargeRewardPoints())+Double.valueOf(axRechargeRecord.getRechargeRewardPoints())),2));
       // axUser.setRemainAmount(  String.format("%.2f",Double.valueOf(axUser.getRemainAmount())+Double.valueOf(axRechargeRecord.getRechargeMoney()),2));
       // axUser.setRemainRewardPoints(  String.format("%.2f",Double.valueOf(axUser.getRemainRewardPoints())+Double.valueOf(axRechargeRecord.getRechargeRewardPoints()),2));

        // 增加客户积分明细
        AxAccountChangeRecord axAccountChangeRecord=new AxAccountChangeRecord();
        axAccountChangeRecord.setOrderNumber(axRechargeRecord.getOrderNumber());
        axAccountChangeRecord.setOrderId(axRechargeRecord.getId()+"");
        axAccountChangeRecord.setChangeSource(changeSouceType.充值.getCode());
        axAccountChangeRecord.setChangeAmount(axRechargeRecord.getRechargeMoney()+"");
        axAccountChangeRecord.setSysuserId(sysUserId);
        axAccountChangeRecord.setChangeSourceName(changeSouceType.充值.name()+"-"+rechargeTypeInfo);
        return  (axAccountChangeRecordService.insertAxAccountChangeRecord(axAccountChangeRecord));

    }
    @Override
    @Transactional
    public  int  userRecharge(AxRechargeRecord axRechargeRecord){

       // 暂无支付接口
         axRechargeRecord.setOrderNumber(getMillseconds());
         axRechargeRecord.setSysUserId(SecurityUtils.getUserId()+"");
         this.insertAxRechargeRecord(axRechargeRecord);
        //增加用户记录；
        // 增加用户余额
        long sysUserId=  SecurityUtils.getUserId();
        SysUser axUser = userService.selectUserById(sysUserId);

        axUser.setRechargeAmount( String.format("%.2f",Double.valueOf(axUser.getRechargeAmount())+Double.valueOf(axRechargeRecord.getRechargeMoney()),2));
        axUser.setRechargeRewardPoints( String.format("%.2f",(Double.valueOf(axUser.getRechargeRewardPoints())+Double.valueOf(axRechargeRecord.getRechargeRewardPoints())),2));
        axUser.setRemainAmount(  String.format("%.2f",Double.valueOf(axUser.getRemainAmount())+Double.valueOf(axRechargeRecord.getRechargeMoney()),2));
        axUser.setRemainRewardPoints(  String.format("%.2f",Double.valueOf(axUser.getRemainRewardPoints())+Double.valueOf(axRechargeRecord.getRechargeRewardPoints()),2));
        userService.updateUser(axUser);
        // 增加客户积分明细

        AxAccountChangeRecord axAccountChangeRecord=new AxAccountChangeRecord();
        axAccountChangeRecord.setOrderNumber(axRechargeRecord.getOrderNumber());
        // axAccountChangeRecord.setOrderNumber(axRechargeRecord.);
//        axAccountChangeRecord.setOrderNumber(axAuthorizationSell.getWpOrderNumber());
//        axAccountChangeRecord.setUnitPrice(axAuthorizationSell.getSellPrice()+"");
//        axAccountChangeRecord.setShopNumber(axAuthorizationSell.getSellNumber());
        axAccountChangeRecord.setOrderId(axRechargeRecord.getId()+"");
        axAccountChangeRecord.setChangeSource(changeSouceType.充值.getCode());
        axAccountChangeRecord.setChangeAmount(axRechargeRecord.getRechargeRewardPoints()+"");
        axAccountChangeRecord.setSysuserId(sysUserId);
        axAccountChangeRecord.setChangeSourceName(changeSouceType.充值.name());
        return  (axAccountChangeRecordService.insertAxAccountChangeRecord(axAccountChangeRecord));
    }

    /**
     * 查询充值记录列表
     * 
     * @param axRechargeRecord 充值记录
     * @return 充值记录
     */
    @Override
    public List<AxRechargeRecord> selectAxRechargeRecordList(AxRechargeRecord axRechargeRecord)
    {
        List<AxRechargeRecord> list =  axRechargeRecordMapper.selectAxRechargeRecordList(axRechargeRecord);
        for(AxRechargeRecord axRechargeRecord1:list){
            axRechargeRecord1.setSysUser( userService.selectUserById(Long.valueOf(axRechargeRecord1.getSysUserId())));
        }
        return list;
    }

    /**
     * 新增充值记录
     * 
     * @param axRechargeRecord 充值记录
     * @return 结果
     */
    @Override
    public int insertAxRechargeRecord(AxRechargeRecord axRechargeRecord)
    {
        axRechargeRecord.setCreateTime(DateUtils.getNowDate());
        axRechargeRecord.setCreateBy(SecurityUtils.getUserId()+"");
        return axRechargeRecordMapper.insertAxRechargeRecord(axRechargeRecord);
    }

    /**
     * 修改充值记录
     * 
     * @param axRechargeRecord 充值记录
     * @return 结果
     */
    @Override
    public int updateAxRechargeRecord(AxRechargeRecord axRechargeRecord)
    {
        axRechargeRecord.setUpdateTime(DateUtils.getNowDate());
        return axRechargeRecordMapper.updateAxRechargeRecord(axRechargeRecord);
    }

    /**
     * 批量删除充值记录
     * 
     * @param ids 需要删除的充值记录主键
     * @return 结果
     */
    @Override
    public int deleteAxRechargeRecordByIds(Long[] ids)
    {
        return axRechargeRecordMapper.deleteAxRechargeRecordByIds(ids);
    }

    /**
     * 删除充值记录信息
     * 
     * @param id 充值记录主键
     * @return 结果
     */
    @Override
    public int deleteAxRechargeRecordById(Long id)
    {
        return axRechargeRecordMapper.deleteAxRechargeRecordById(id);
    }

    // 微信获取支付参数
    @Override
    public String getWxPaySign(AxRechargeRecord axRechargeRecord){
        axRechargeRecord.setOrderNumber(getMillseconds());
        axRechargeRecord.setSysUserId(SecurityUtils.getUserId()+"");
        axRechargeRecord.setPayWay(payTypeEnum.微信.getInfo());
        axRechargeRecord.setPayStatus(PayStatusEnum.待支付.getCode());
        this.insertAxRechargeRecord(axRechargeRecord);
        String wxpayURL=this.getWxPayUrl(axRechargeRecord);
        return  wxpayURL;
    }


    @Override
    public String getZfbPaySign(AxRechargeRecord axRechargeRecord){
        axRechargeRecord.setOrderNumber(getMillseconds());
        axRechargeRecord.setSysUserId(SecurityUtils.getUserId()+"");
        axRechargeRecord.setPayWay(payTypeEnum.支付宝.getInfo());
        axRechargeRecord.setPayStatus(PayStatusEnum.待支付.getCode());
        this.insertAxRechargeRecord(axRechargeRecord);
        String terminalCode="10806301";
        String key="70609712";
        String nonceStr="fe1751949d";
        String payParams ="amount=" +axRechargeRecord.getRechargeMoney()+
                "&nonceStr=" +nonceStr+
                "&notifyUrl=https://pcmag.dpdzsw.com/prod-api/ax/axRechargeRecord/wxPayNotify" +
                "&outTradeNo="+axRechargeRecord.getId()+
                "&terminalCode=" +terminalCode+
                "&key="+key;
        // &terminalCode=10806301&key=70609712
        String sign = Md5Utils.toHex(Md5Utils.md5(payParams));
        String zfbUrl="/pages/pay/index?amount="+axRechargeRecord.getRechargeMoney()+"&nonceStr="+nonceStr+"&outTradeNo="+axRechargeRecord.getId()+
                "&notifyUrl=https://pcmag.dpdzsw.com/prod-api/ax/axRechargeRecord/wxPayNotify&terminalCode="+terminalCode+"&sign="+sign;
        return  zfbUrl;
    }



    public  String  getWxPayUrl(AxRechargeRecord axRechargeRecord){
        String amount=axRechargeRecord.getRechargeMoney();
        //String orderNumber="157";
        String terminalCode="10806301";
        String key="70609712";
        String nonceStr="fe1751949d";
        String payParams ="amount=" +amount+
                "&nonceStr=" +nonceStr+
                "&notifyUrl=https://pcmag.dpdzsw.com/prod-api/ax/axRechargeRecord/wxPayNotify" +
                "&outTradeNo="+axRechargeRecord.getId()+
                "&terminalCode=" +terminalCode+
                "&key="+key;
        // &terminalCode=10806301&key=70609712
        String sign = Md5Utils.toHex(Md5Utils.md5(payParams));

        HashMap<String, Object> params = new HashMap<>();
        params.put("terminalCode",terminalCode);
        params.put("nonceStr",nonceStr);
        params.put("outTradeNo",axRechargeRecord.getId());
        params.put("notifyUrl","https://pcmag.dpdzsw.com/prod-api/ax/axRechargeRecord/wxPayNotify");
        params.put("sign",sign);
        params.put( "amount",amount);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(params);
            String resultStr = HttpClientSslUtils.doPost("https://www.yqdfpay.com/api/third/v2.0/pay/scheme", jsonString);
            /// String resultStr = HttpClientSslUtils.doPost("https://www.yqdfpay.com/api/third/v2.0/pay/qr", jsonString);
            System.out.println(resultStr);
            JSONObject object = JSONObject.parseObject(resultStr);
            System.out.println(object.get("openLink").toString());
            return object.get("openLink").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new GlobalException("支付失败");
    }

    // 微信支付回调
    @Transactional
    @Override
    public  String   rechargeWxPayNotify(HttpServletRequest request, HttpServletResponse response){
        BufferedReader br = null;
        System.out.println("充值回调111111111111111111111111-----------------"+request.getParameter("status"));
        try {
            BufferedReader reader = request.getReader();
            String line = null;
            StringBuilder content = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            String bodyContent = content.toString();
            System.out.println("开始回调*****：：：：：：：：：：：：："+bodyContent);
            JSONObject object = JSONObject.parseObject(bodyContent);
            String outTradeNo =object.getString("outTradeNo");
            AxRechargeRecord axRechargeRecord = axRechargeRecordMapper.selectAxRechargeRecordById(Long.valueOf(outTradeNo));
            //更改账户余额
            SysUser rechargeUser= userService.selectUserById(Long.valueOf(axRechargeRecord.getSysUserId()));
            Double remainMoney= Double.valueOf(rechargeUser.getRechargeAmount())+Double.valueOf(axRechargeRecord.getRechargeMoney());
            rechargeUser.setRechargeAmount(String.format("%.2f",remainMoney));
            userService.updateUser(rechargeUser);
            // 更改支付状态
            axRechargeRecord.setPayStatus(PayStatusEnum.已支付.getCode());
            axRechargeRecord.setPayTime(new Date());
            axRechargeRecordMapper.updateAxRechargeRecord(axRechargeRecord);

            //新增变动记录
            AxAccountChangeRecord axAccountChangeRecord=new AxAccountChangeRecord();
            axAccountChangeRecord.setOrderNumber(axRechargeRecord.getOrderNumber());
          //  axAccountChangeRecord.setUnitPrice(axOrder.getPrice()+"");
           // axAccountChangeRecord.setShopNumber(axOrder.getTotalNum());
            axAccountChangeRecord.setOrderId(axRechargeRecord.getId()+"");
            axAccountChangeRecord.setChangeSource(changeSouceType.充值.getCode());
          //  axAccountChangeRecord.setGoodId(axOrder.getGoodId());
            axAccountChangeRecord.setChangeAmount(axRechargeRecord.getRechargeMoney());
            axAccountChangeRecord.setChangeSourceName(changeSouceType.充值.name());
            axAccountChangeRecord.setSysuserId(Long.valueOf(axRechargeRecord.getSysUserId()));
            axAccountChangeRecord.setIncome("0");
            axAccountChangeRecord.setIncomeRate("0");
            axAccountChangeRecordService.insertAxAccountChangeRecord(axAccountChangeRecord);
            return "SUCCESS";

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "SUCCESS";
    }


    public String getMillseconds(){
        String  secondMills= System.currentTimeMillis()+"";
        secondMills=secondMills.substring(secondMills.length()-4,secondMills.length());
        return secondMills;
    }
}
